package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 0/15 * * * ?")
    public void processOutTime0rders(){
        //处理超时订单
        //1.查询数据库orders表，条件:状态-待付款，下单时间<当前时间-15分钟
        LocalDateTime  time = LocalDateTime.now().minusMinutes(1);//15分钟前的时间
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时,自动取消订单");
                orders.setCancelTime(LocalDateTime.now());
                log.info("自动取消超时订单{}",orders.getId());
                //更新订单状态
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "1 * * * * ?")//  每分钟执行一次测试用
    public void processOutTimeConfirmOrder(){
        //处理待接单订单
        //1.查询数据库orders表，条件:状态-派送中，下单时间<当前时间-1天
        LocalDateTime  time = LocalDateTime.now().minusDays(1);//1天前的时间
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);//将状态为派送中的订单查询出来
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);//订单状态改为已完成
                orders.setDeliveryTime(LocalDateTime.now());//订单完成时间
                log.info("自动完成订单:{}",orders.getId());
                //更新订单状态
                orderMapper.update(orders);
            }
        }
    }
}
